package com.laivi.basic.model.orm;

import java.lang.reflect.Field;

import com.laivi.basic.annotation.orm.Column;
import com.laivi.basic.annotation.orm.Table;
import com.laivi.basic.annotation.orm.Transient;
import com.laivi.basic.type.orm.GenerateMySqlColumn;
import com.laivi.basic.util.DataUtil;
import com.laivi.basic.util.LangUtil;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-5
 * description:
 */
public class GenerateMysqlTable implements IGenerateTable {

	@Override
	public String generateCreate(Class<?> klass) {
		Table table=klass.getAnnotation(Table.class);
		if(null!=table){
			StringBuffer sql=new StringBuffer("create table if not exists "+table.value()+"(");
			for(Field field:LangUtil.getFields(klass)){
				Transient tran=field.getAnnotation(Transient.class);
				if(tran==null){
					sql.append(gengerateField(field)+",");
				}
				
			}
			sql=new StringBuffer(sql.substring(0, sql.length()-1));
			sql.append(")");
			return sql.toString();
		}
		
		return null;
	}

	@Override
	public String generateUpdate(Class<?> klass) {
		return null;
	}
	
	public String gengerateField(Field field){
		StringBuffer fields=new StringBuffer();
		Column column=field.getAnnotation(Column.class);
		String columnName=null;
		if(column!=null && !DataUtil.isEmpty(column.name())){
			columnName=column.name();
		}else{
			columnName=field.getName();
		}
		
		if(column!=null && column.many()){
			
		}else if(column!=null && column.one()){
			fields.append(columnName+" bigint(64) DEFAULT NULL");
		}else{
			if(field.getType().isEnum()){
				fields.append(columnName+" nvarchar(30)");
				if(null==column||column.nullable()){
					fields.append(" DEFAULT NULL");
				}
			}else if(null!=column && column.longtext()){
				fields.append(columnName+" longtext");
				if(null!=column||column.nullable()){
					fields.append(" DEFAULT NULL");
				}
			}else if(null!=column && column.id()){
				fields.append(columnName+" "+GenerateMySqlColumn.fromType(field.getType().toString()).toColumn()+" NOT NULL AUTO_INCREMENT");
			}else{
				if("STRING".equals(field.getType().toString())){
					if(column!=null){
						fields.append(columnName+" nvarchar("+column.length()+")");
					}else{
						fields.append(columnName+" nvarchar(255)");
					}
				}else{
					fields.append(columnName+" "+GenerateMySqlColumn.fromType(field.getType().toString()).toColumn());
				}
				
				if(column==null||column.nullable()){
					fields.append(" DEFAULT NULL");
				}
			}
			if(null!=column&& !DataUtil.isEmpty(column.comments())){
				fields.append(" COMMENT '"+column.comments()+"'");
			}
			if(null!=column && column.id()){
				fields.append(",PRIMARY KEY ("+columnName+")");
			}
		}
		return fields.toString();
	}

	@Override
	public String generateComments(Class<?> klass) {
		return null;
	}

}
